package cn.tedu._06article.base.exception;


import cn.tedu._06article.base.response.JsonResult;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
//    @ExceptionHandler(RuntimeException.class)
//    public JsonResult doRuntimeException(RuntimeException ex) {
//        log.debug("发生RuntimeException异常");
//        String data=ex.getMessage().split(":")[1].trim();
//        return JsonResult.fail(data);
//    }

    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex) {
        log.debug("发生ConstraintViolationException异常");
        //String data=ex.getConstraintViolations().iterator().next().getMessage();
        String data=ex.getMessage().split(":")[1].trim();
        return JsonResult.fail(data);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        log.debug("发生MethodArgumentNotValidException异常");
        String data=ex.getFieldError().getDefaultMessage();
        //String data=ex.getBindingResult().getFieldError().getDefaultMessage();
        return JsonResult.fail(data);
    }
}
